<template>
  <div class="attri-component">
    <el-card class="box-card">
      <!--      选择在售商品-->
      <el-form :inline="true" :model="goodAttrObj" class="demo-form-inline">
        <el-form-item label="商品id">
          <el-input v-model="goodAttrObj.id" readonly></el-input>
        </el-form-item>
        <el-form-item label="商品名">
          <el-input v-model="goodAttrObj.name" readonly></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sellingGoodsDialogVisible = true">选择商品</el-button>
        </el-form-item>
      </el-form>
<!--      商品属性以及该属性下的属性选项值 及售价-->
      <h4>属性及售价</h4>
      <div class="attr-choice-area" v-for="item in attrList" :key="item.attrid">
        <span>{{ item.attrname }}</span>
        <el-button type="primary" size="small" style="margin-left: 50px" @click="addNewChoice(item.attrid)">新增属性选项值</el-button>
        <div class="choice-area">
          <el-row :gutter="20">
            <el-col :span="goodsAtrrAndChoiceList.filter(val => val.attrname === item.attrname).length >= 4 ? 6 : 24 / goodsAtrrAndChoiceList.filter(val => val.attrname === item.attrname).length" v-for="item2 in goodsAtrrAndChoiceList.filter(val => val.attrname === item.attrname)" :key="item2.choiceid">
              <div class="grid-content bg-purple">
                <el-tag>{{ item2.choicename }}</el-tag>
                <el-input-number v-model="item2.choiceprice" :controls="false" title="该属性与基础价的差值" @change="changeCurrentPrice(item2.choiceid, $event)"></el-input-number>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
<!--      商品属性选项值之间的搭配-->
      <h4>搭配</h4>
      <div class="collocation">
        <el-tag v-for="item in choiceCollocation" :key="item.invenid">{{ item.chiocename }}</el-tag>
        <el-button type="primary" size="small" @click="addNewCollocation">新增搭配</el-button>
      </div>
    </el-card>
    <!--    选择商品的Dialog对话框-->
    <el-dialog title="在售商品列表" :visible.sync="sellingGoodsDialogVisible">
      <!--      分页模块-->
      <el-pagination
        :page-size="4"
        layout="prev, pager, next"
        :total="sellingGoodsList.length"
        @current-change="changePageNum">
      </el-pagination>
      <el-table :data="readyToRenderGoodsList">
        <el-table-column property="goodsid" label="商品id" width="80"></el-table-column>
        <el-table-column property="goodsname" label="商品名" min-width="350"></el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <el-button @click="chosenCurrentChoice(scope.row)" aria-rowindex="80">确定</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
<!--    新增搭配的属性选项值dialog对话框-->
    <el-dialog
      title="属性组合"
      :visible.sync="collocationDialogVisible"
      width="50%"
      @close="closeCollocationDialog"
      >
      <div class="attr-choice-area" v-for="(item, index) in attrList" :key="item.attrid">
        <span >{{ item.attrname }}</span>
        <div class="choice-area">
          <el-select v-model="choiceList[index]" :placeholder="'选择' + item.attrname">
            <el-option
              v-for="item2 in goodsAtrrAndChoiceList.filter(val => val.attrid === item.attrid)"
              :key="item2.choiceid"
              :label="item2.choicename"
              :value="item2.choiceid">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="attr-choice-area">
        <span>初始库存量</span>
        <div class="choice-area">
          <el-input type="number" v-model="invenNum"></el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="collocationDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCurrentCollocation">确 定</el-button>
      </span>
    </el-dialog>
<!--    在商品属性id已知情况下 在当前商品属性下新增商品属性选项值的dialog对话框-->
    <el-dialog
      title="提示"
      :visible.sync="newChoiceDialogVisible"
      width="50%">
      <div class="attr-choice-area">
        <span>属性选项值名</span>
        <div class="choice-area">
          <el-input v-model="newChoiceObj.name"></el-input>
        </div>
      </div>
      <div class="attr-choice-area">
        <span>与基本价差价</span>
        <div class="choice-area">
          <el-input type="number" v-model="newChoiceObj.price"></el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeNewChoiceDIalog">取 消</el-button>
        <el-button type="primary" @click="submitNewChoice">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'Attribute',
  created() {
    this.getMerchantSellingGoods()
    this.$notify({
      title: '提示',
      message: '保证每个商品属性下的选项有且仅有一个售价为0的选项，否则商品基价不正常工作',
      duration: 3000
    })
  },
  data() {
    return {
      // 当前正在查看的商品属性选项值库存的商品信息
      goodAttrObj: {
        id: '',
        name: ''
      },
      // 控制展示商家售卖的商品信息对话框是否可见
      sellingGoodsDialogVisible: false,
      // 商品属性以及属性选项值列表
      goodsAtrrAndChoiceList: [],
      // 商品属性选项值之间的组合
      choiceCollocation: [],
      // 控制属性选择dialog对话框是否可见
      collocationDialogVisible: false,
      // 当前用户在新增搭配dialog对话框中选择的属性选项值列表
      choiceList: [],
      // 当前用户在新增搭配dialog对话框中填写的属性选项值组合初始库存量
      invenNum: 0,
      // 当前正欲为该属性添加新的属性选项值的属性id
      currentChosenAttrid: '',
      // 控制展示新增商品属性选项值dialog对话框是否可见
      newChoiceDialogVisible: false,
      // 新增商品属性选项值的表单对象
      newChoiceObj: {
        name: '',
        price: ''
      },
      readyToRenderGoodsList: []
    }
  },
  computed: {
    ...mapState(['sellingGoodsList']),
    attrList() {
      const arr = []
      const attridArr = []
      for (const item of this.goodsAtrrAndChoiceList) {
        if (attridArr.indexOf(item.attrid) >= 0) continue
        attridArr.push(item.attrid)
        arr.push({ attrid: item.attrid, attrname: item.attrname })
      }
      return arr
    }
  },
  methods: {
    ...mapMutations(['setSellingGoodsList']),
    async getMerchantSellingGoods() {
      if (this.sellingGoodsList.length > 0) {
        this.readyToRenderGoodsList = this.sellingGoodsList.slice(0, 4)
        return this.showDefaultAttr()
      }
      console.log('发起远程请求商品数据 属性页')
      if (!sessionStorage.getItem('id')) return this.$message.error('状态异常')
      const { data: res } = await this.$http.get('/merchant/goods', {
        params: {
          id: sessionStorage.getItem('id')
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品信息失败')
      this.setSellingGoodsList(res.recordset)
      this.readyToRenderGoodsList = this.sellingGoodsList.slice(0, 4)
      this.showDefaultAttr()
    },
    // 表格中的确定按钮被点击时 保存用户点击的商品信息
    chosenCurrentChoice(good) {
      this.goodAttrObj.id = good.goodsid
      this.goodAttrObj.name = good.goodsname
      this.sellingGoodsDialogVisible = false
      this.getChosenGoodDetail(this.goodAttrObj.id)
    },
    // 当选择商品界面的确定按钮被点击时触发
    async getChosenGoodDetail(id) {
      console.log('Yes')
      const { data: res } = await this.$http.get('/merchant/goodsdetail', {
        params: {
          id
        }
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取详细信息失败')
      this.goodsAtrrAndChoiceList = res.recordset.sort((lastVal, nextVal) => lastVal.choiceprice - nextVal.choiceprice)
      this.choiceCollocation = res.recordsets[1]
    },
    // 展示默认此商家第一个售卖商品的属性管理信息界面
    showDefaultAttr() {
      this.goodAttrObj.id = this.sellingGoodsList[0].goodsid
      this.goodAttrObj.name = this.sellingGoodsList[0].goodsname
      this.getChosenGoodDetail(this.goodAttrObj.id)
    },
    // 新增搭配被点击时触发
    addNewCollocation() {
      this.collocationDialogVisible = true
    },
    // 新增搭配dialog对话框被关闭时触发
    closeCollocationDialog() {
      this.collocationDialogVisible = false
      this.choiceList = []

      this.getChosenGoodDetail(this.goodAttrObj.id)
    },
    // 新增搭配dialog对话框中的确定按钮被点击时触发
    async submitCurrentCollocation() {
      if (this.choiceCollocation.findIndex(item => item.attrchoiceid === this.choiceList.join(',')) >= 0) return this.$message.info('此组合已存在')
      const { data: res } = await this.$http.post('/inven/new', {
        gid: this.goodAttrObj.id,
        cids: this.choiceList.join(','),
        h: this.invenNum
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.message)
      this.$message.success('新增此组合成功')
      this.closeCollocationDialog()
    },
    // 新增属性选项值按钮被点击时触发 在当前商品属性下新增属性选项值
    addNewChoice(id) {
      this.currentChosenAttrid = id
      this.newChoiceDialogVisible = true
    },
    closeNewChoiceDIalog() {
      this.newChoiceDialogVisible = false
      this.currentChosenAttrid = ''
      this.newChoiceObj = {}
      this.getChosenGoodDetail(this.goodAttrObj.id)
    },
    // 当新增商品属性选项值对话框中的确定按钮被点击时触发，将用户新增的属性选项值表单对象添加
    async submitNewChoice() {
      if (this.newChoiceObj.name.trim() === '' || this.newChoiceObj.price < 0) return this.$message.error('请检查所填写表单')
      const { data: res } = await this.$http.post('/choice/add', {
        aid: this.currentChosenAttrid,
        name: this.newChoiceObj.name,
        cprice: this.newChoiceObj.price
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.message)
      console.log(res)
      this.closeNewChoiceDIalog()
    },
    // 商品属性选项值售价发生改变时触发
    async changeCurrentPrice(id, price) {
      const { data: res } = await this.$http.put('/choice/modify', { id, price })
      if (res.meta.status !== 200) return this.$message.error('修改售价失败')
      this.$message.success('修改售价成功')
    },
    // dialog对话框中分页模块当前页数发生改变时触发
    changePageNum(currentPage) {
      this.currentPageNum = currentPage
      this.readyToRenderGoodsList = this.sellingGoodsList.slice((this.currentPageNum - 1) * 4, this.currentPageNum * 4)
    }
  }
}
</script>

<style scoped lang="less">
.el-form--inline .el-form-item:nth-child(2) .el-input {
  width: 1000px;
}

.el-col {
  margin-top: 15px;
}

.choice-area {
  padding: 20px;
  .el-tag {
    margin-right: 10px;
  }
}

.attr-choice-area {
  text-align: left;
}

.collocation {
  text-align: left;
  .el-table,
  .el-input {
    padding: 20px;
  }
  .el-select,
  .el-tag {
    margin: 10px;
  }
}
</style>
